package com.ssy.lingxi.platform.manage.serviceimpl.paas;

import cn.hutool.json.JSONUtil;
import com.ssy.lingxi.common.constant.Constants;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.component.redis.service.IRedisStringUtils;
import com.ssy.lingxi.platform.manage.api.model.dto.site.SitePAASDTO;
import com.ssy.lingxi.platform.manage.constant.CommonBooleanEnum;
import com.ssy.lingxi.platform.manage.entity.base.Shop;
import com.ssy.lingxi.platform.manage.entity.base.Site;
import com.ssy.lingxi.platform.manage.entity.base.SiteShop;
import com.ssy.lingxi.platform.manage.repository.ShopRepository;
import com.ssy.lingxi.platform.manage.repository.SiteRepository;
import com.ssy.lingxi.platform.manage.repository.SiteShopRepository;
import com.ssy.lingxi.platform.manage.service.IShopService;
import com.ssy.lingxi.platform.manage.service.paas.ISitePAASService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 站点 - （系统初始化）PAAS接口 - 业务实现层
 *
 * @author fhj
 * @version 2.0.0
 * @date 2020/9/28
 */
@Service
public class SitePAASServiceImpl implements ISitePAASService {

    @Resource
    private SiteRepository siteRepository;
    @Resource
    private SiteShopRepository siteShopRepository;
    @Resource
    private ShopRepository shopRepository;
    @Resource
    private IShopService shopService;
    @Resource
    private IRedisStringUtils redisStringUtils;

    @Override
    @Transactional
    public Wrapper<Void> add(SitePAASDTO dto) {
        //新增
        Site site = new Site();
        BeanUtils.copyProperties(dto, site);
        siteRepository.saveAndFlush(site);

        //新增站点与商城的关联数据
        List<SiteShop> siteShops = new ArrayList<>();
        dto.getShopIds().forEach(shopId -> {
            SiteShop siteShop = new SiteShop();
            siteShop.setShopId(shopId);
            siteShop.setSiteId(site.getId());
            siteShops.add(siteShop);
        });
        siteShopRepository.saveAll(siteShops);

        //缓存数据到redis
        updateRedisInfo(dto.getId(), dto.getShopIds());

        return Wrapper.success();
    }

    @Override
    @Transactional
    public Wrapper<Void> update(SitePAASDTO dto) {
        //获取站点
        Site site = siteRepository.findById(dto.getId()).orElse(null);
        if (site == null) {
            throw new BusinessException(ResponseCode.MAN_RECORDS_DON_T_EXIST);
        }

        //修改
        BeanUtils.copyProperties(dto, site);
        siteRepository.saveAndFlush(site);

        //先清空站点关联的商城数据, 再重新新增
        siteShopRepository.deleteAllBySiteId(site.getId());
        List<SiteShop> siteShop = new ArrayList<>();
        dto.getShopIds().forEach(id -> {
            SiteShop ss = new SiteShop();
            ss.setSiteId(site.getId());
            ss.setShopId(id);
            siteShop.add(ss);
        });
        siteShopRepository.saveAll(siteShop);

        //缓存数据到redis
        updateRedisInfo(dto.getId(), dto.getShopIds());

        return Wrapper.success();
    }

    @Override
    @Transactional
    public Wrapper<Void> updateState(SitePAASDTO dto) {
        //获取站点
        Site site = siteRepository.findById(dto.getId()).orElse(null);
        if (site == null) {
            throw new BusinessException(ResponseCode.MAN_RECORDS_DON_T_EXIST);
        }

        //修改状态
        site.setId(dto.getId());
        site.setState(dto.getState());
        siteRepository.saveAndFlush(site);

        //更新缓存信息
        if (dto.getState().equals(CommonBooleanEnum.YES.getCode())) {
            List<SiteShop> siteShopList = siteShopRepository.findBySiteId(site.getId());
            if (siteShopList != null && siteShopList.size() > 0) {
                List<Long> shopIdList = siteShopList.stream().map(SiteShop::getShopId).collect(Collectors.toList());
                updateRedisInfo(site.getId(), shopIdList);
            }
        } else {
            redisStringUtils.del(Constants.REDIS_KEY_SITE + site.getId(), Constants.REDIS_PLATFORM_MANAGE_INDEX);
        }
        return Wrapper.success();
    }

    @Override
    @Transactional
    public Wrapper<Void> delete(SitePAASDTO dto) {
        //获取站点
        Site site = siteRepository.findById(dto.getId()).orElse(null);
        if (site == null) {
            throw new BusinessException(ResponseCode.MAN_RECORDS_DON_T_EXIST);
        }

        //删除
        siteRepository.delete(site);

        //删除redis缓存数据
        redisStringUtils.del(Constants.REDIS_KEY_SITE + dto.getId(), Constants.REDIS_PLATFORM_MANAGE_INDEX);
        return Wrapper.success();
    }

    /**
     * 更新redis中的数据
     */
    private void updateRedisInfo(Long siteId, List<Long> shopIdList) {
        if (shopIdList != null && !shopIdList.isEmpty()) {
            List<Shop> shopList = shopRepository.findByIdIn(shopIdList);
            Map<String, String> map = new HashMap<>();
            shopList.forEach(shop -> {
                map.put(String.valueOf(shop.getId()), JSONUtil.toJsonStr(shop));
            });
            redisStringUtils.hMSet(Constants.REDIS_KEY_SITE + siteId, map, Constants.REDIS_PLATFORM_MANAGE_INDEX);
        } else {
            //删除redis缓存数据
            redisStringUtils.del(Constants.REDIS_KEY_SITE + siteId, Constants.REDIS_PLATFORM_MANAGE_INDEX);
        }
        //更新redis商城数据
        shopService.initToRedis();
    }
}
